<template>
  <div class="mod-config">
    <el-card class="box-card search-input" shadow="never">
      <el-form  label-width="120px" ref="dataForm" size="mini" :model="dataForm" @keyup.enter.native="findPage()">
        <el-row>
          <el-col :span="6">
            <el-form-item label="主播手机号：" prop="account">
              <el-input v-model="dataForm.account"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主播姓名：" prop="name">
              <el-input v-model="dataForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主播状态：" prop="status">
              <cy-select url="/api/v1/broadcast/config/anchor_status/val" :all-option="true" v-model="dataForm.status"></cy-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button  type="primary" @click="$refs.CyTable.query(dataForm)">查询</el-button>
              <el-button @click="reset()">重置</el-button>
              <el-button  type="primary" @click="dialogVisibleAdd=true">申请主播</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <cy-table
      url="/api/v1/broadcast/shopAnchorInfo/"
      :max-height="500"
      :showBatchDelete="false"
      :showSelection="false"
      :highlightCurrentRow="true"
      :operationWidth="300"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showDetailOperation="true"
      :showEditOperation="false"
      :showDeleteOperation="true"
      :showCheckCustomOperation="true"
      showCheckCustomLabel="status"
      showCheckCustomLabelVal="23/24/25/26"
      customBtbLable="禁播/禁播/禁播/取消禁播"
      @handleDelete="handleDelete"
      @findPage="findPage"
      @handleBtbCustom="handleBtbCustom"
      @handleDetail="handleDetail"
      ref="CyTable"
    >
    </cy-table>
    <el-dialog
      width="80%"
      title="主播详情"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible">
      <el-card class="box-card" shadow="never">
        <el-form label-position="left" label-width="120px" ref="detailData" size="mini" :rules="rules" :model="detailData">
          <el-row>
            <el-col :span="8">
              <el-form-item label="主播姓名：" prop="name">
                <span>{{detailData.name}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主播手机：" prop="account">
                <span>{{detailData.account}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主播身份证：" prop="identityCode">
                <span>{{detailData.identityCode}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关注人数：" prop="userFollowCount">
                <span>{{detailData.userFollowCount}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="直播场数：" prop="liveCount">
                <span>{{detailData.liveCount}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <img :src="detailData.pic" style="width: 100px;height: 100px"/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <h3>历史直播</h3>
            </el-col>
            <el-col :span="24">
              <div style="margin-top: 15px;">
                <el-button size="mini" :type="label==0?'primary':''" round @click="getPageAnchorLiveInfo(0)">全部</el-button>
                <el-button size="mini" :type="label==16?'primary':''" round @click="getPageAnchorLiveInfo(16)">进行中</el-button>
                <el-button size="mini" :type="label==15?'primary':''" round @click="getPageAnchorLiveInfo(15)">未开始</el-button>
                <el-button size="mini" :type="label==17?'primary':''" round @click="getPageAnchorLiveInfo(17)">已结束</el-button>
              </div>
            </el-col>
          </el-row>

          <el-table
            :data="detailData.liveInfos.rows"
            style="width: 100%">
            <el-table-column
              prop="id"
              label="序号"
              header-align="center"
              align="center"
              width="180">
            </el-table-column>
            <el-table-column
              prop="title"
              label="直播主题"
              header-align="center"
              align="center"
              width="180">
            </el-table-column>
            <el-table-column
              prop="startTime"
              label="直播开始时间"
              header-align="center"
              align="center"
              width="260">
            </el-table-column>
            <el-table-column
              prop="actualEndTime"
              header-align="center"
              align="center"
              label="直播结束时间"
              width="260">
            </el-table-column>
            <el-table-column
              prop="duration"
              header-align="center"
              align="center"
              label="直播时长">
            </el-table-column>
            <el-table-column
              prop="statusValue"
              header-align="center"
              align="center"
              label="直播状态">
            </el-table-column>
          </el-table>
          <div style="padding: 15px;text-align: right;">
            <el-pagination
              layout="total, prev, pager, next, jumper,sizes"
              @current-change="refreshPageRequest2"
              :current-page="pageRequest2.pageNum"
              :page-size="pageRequest2.pageSize"
              :total="totalSize2"
              :page-sizes="[10,20,30,40]"
              @size-change="handleSizeChange2"
            ></el-pagination>
          </div>
        </el-form>
      </el-card>
    </el-dialog>

    <el-dialog
      width="50%"
      title="申请主播"
      :close-on-click-modal="false"
      @close="dialogClose"
      :visible.sync="dialogVisibleAdd">
      <el-card v-loading="addLoading" class="box-card" shadow="never">
        <el-form label-width="160px" ref="addDataForm" size="mini" :rules="addRules" :model="addDataForm">
          <el-col :span="20">
            <el-form-item label="主播姓名：" prop="name">
              <el-input v-model="addDataForm.name"  maxlength="20" placeholder="最多可编辑20个字" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="主播手机：" prop="account">
              <el-input maxlength="11" placeholder="请输入11位手机号" v-model="addDataForm.account"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="主播身份证：" prop="identityCode">
              <el-input maxlength="18" placeholder="请输入18位有效身份证" v-model="addDataForm.identityCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-col :span="24">
              <el-form-item label="手持身份证照片：" prop="handPhoto">
                <cy-file-upload
                  v-model="addDataForm.handPhoto"
                  @onSuccess="fileUploadSuccess"
                  :before-upload="beforeAvatarUpload"
                ></cy-file-upload>
                <div style="font-size: 12px">只能上传jpg/png文件，且不超过5M. 图片尺寸1920*1080px</div>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="10" offset="8">
            <el-button size="mini"  @click="dialogClose">取消</el-button>
            <el-button size="mini"  type="primary" @click="addDataFormSubmit()">确定</el-button>
          </el-col>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>
<script>
  import CyTable from "./component/CyTable";
  import CySelect from "./component/CySelect";
  import CyFileUpload from "./component/CyFileUpload";
  export default {
    components: {
      CyTable,
      CySelect,
      CyFileUpload
    },
    data() {
      return {
        pageRequest2:{
          pageNum:1,
          pageSize:10
        },
        label:0,
        totalSize2:0,
        detailData:{
          liveInfos:{
            rows:[]
          }
        },
        addDataForm:{
          handPhoto:"",
        },
        dialogVisibleAdd:false,
        loading: false,
        addLoading: false,
        moreBtnDisable: true,
        dataForm: {
        },
        columns: [],
        filterColumns: [],
        pageRequest: { pageNum: 1, pageSize: 10 },
        totalSize: 0,
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        rules : {
        },
        addRules : {
          account: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            {
              validator:this.verifyAnchor,
              trigger: 'blur'
            }
          ],
          identityCode: [
            { required: true, message: '身份证号不能为空', trigger: 'blur' },
            {
              pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
              message: '证件号码格式有误！',
              trigger: 'blur'
            }
          ],
          name: [{ required: true, message: '主播真实姓名不能为空', trigger: 'blur' }],
          handPhoto:[{ required: true, message: '请上传手持身份证照片',trigger: 'blur' }]
        },
      }
    },
    mounted: function () {
      this.columns = [
        { prop: "id", label: "主播ID", minWidth: 120 },
        { prop: "number", label: "主播编码", minWidth: 120 },
        { prop: "account", label: "主播手机号", minWidth: 120 },
        { prop: "name", label: "主播姓名", minWidth: 120},
        { prop: "userFollowCount", label: "关注人数", minWidth: 120 , formatter: this.defaultVal},
        { prop: "liveCount", label: "直播场数", minWidth: 120, formatter: this.defaultVal},
        { prop: "statusValue", label: "主播状态", minWidth: 120},
      ];
      let temp = [];
      this.columns.forEach(function(key, val) {
        temp.push(key);
      });
      this.filterColumns = temp;
    },
    methods: {
      defaultVal(row, column, cellValue, index) {
        //默认值 0
        if (cellValue == null || cellValue == '') {
          return 0;
        }
        return cellValue;
      },
      // 获取数据列表
      findPage() {
        this.$refs.CyTable.findPage(this.dataForm);
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.findPage()
      },
      //重置
      reset() {
        this.dataForm={};
        this.$refs.CyTable.resetForm(this.dataForm);
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.findPage()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
        if (this.dataListSelections.length > 0) {
          this.moreBtnDisable = false
        } else {
          this.moreBtnDisable = true
        }
      },
      // 删除
      handleDelete: function (params) {
        let ids = params.params;
        let delDataForm = [];
        ids.forEach(val => {
          delDataForm.push(val)
        })
        if (delDataForm.length > 0) {
          let this_ = this;
          this.utils.request.liveRequest({
            url: '/api/v1/broadcast/anchorInfo/batchDelete',
            method: 'post',
            params: delDataForm,
          }).then(result => {
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
            }
          })
        } else {
          this.$message({message: "请选择需要删除的数据", type: "info"});
        }

      },
      // 详情
      handleDetail: function (params) {
        let id = params.row.id;
        let param = { "id": id}
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/getAnchorInfoById/'+id,
          method: 'get',
          params: param,
        }).then(result => {
          this.dialogVisible = true;
          this.detailData = result.data.data;
          this.totalSize2 = result.data.data.liveInfos.total;
          this.$forceUpdate();
        })
      },
      //自定义按钮
      handleBtbCustom:function(params){
        let status = params.row.status;
        let banAnchor="确认禁播吗？";
        if(status==26){
          banAnchor="确认取消禁播吗？";
        }
        this.$confirm(banAnchor, "提示", {type:'warning'}).then(() => {
          this.loading=true;
          let id = params.row.id;
          let param = {"id": id, "status": status};
          let this_ = this;
          this.utils.request.liveRequest({
            url: '/api/v1/broadcast/anchorInfo/banAnchor',
            method: 'post',
            params: param,
          }).then(result => {
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
            this.loading=false;
          })
        });
      },
      verifyAnchor(rule, value, callback){
        if(!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)){
          callback(new Error('手机号格式不对'));
        } else {
          let param = {"account": value};
          this.utils.request.liveRequest({
            url: '/api/v1/broadcast/anchorInfo/verifyAnchor',
            method: 'post',
            params: param
          }).then(result => {
            let data = result.data;
            if (data.data == '1') {
              callback(new Error('手机号已经为平台主播了'));
            }else if (data.data == '2') {
              callback(new Error('该手机正在审核中'));
            }else if (data.data == '3') {
              callback(new Error('该手机号还未注册为来伊份会员'));
            }else{
              callback();
            }

          })
        }
      },
      refreshPageRequest2: function (pageNum) {
        this.pageRequest2.pageNum = pageNum;
        this.findPageAnchorLiveInfo(this.label)
      },
      handleSizeChange2: function (pageSize) {
        this.pageRequest2.pageSize = pageSize;
        this.pageRequest2.pageNum = 1;
        let label =  this.label;
        this.findPageAnchorLiveInfo(label)
      },
      getPageAnchorLiveInfo(label){
        this.label= label;
        this.handleSizeChange2();
      },
      findPageAnchorLiveInfo(label){
        let this_=this;
        let  pageNum=this.pageRequest2.pageNum;
        let  pageSize= this.pageRequest2.pageSize;
        let detailLiveList={"anchorId":this_.detailData.id,"status":label,"pageSize":pageSize,"pageNum":pageNum};
        this.utils.request.liveRequest({
          url: '/api/v1/liveInfo/list',
          method: 'get',
          params: detailLiveList
        }).then(result => {
          let data = result.data;
          if (data && data.code === '0') {
            this_.detailData.liveInfos.rows = data.data.rows;
            this.totalSize2=data.data.total;
            this_.$forceUpdate();
          } else {
            this_.dataList = []
            this_.totalPage = 0
          }
          this_.dataListLoading = false
        });
      },
      addDataFormSubmit: function() {
        let this_=this;
        this.$refs.addDataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              this_.addLoading=true;
              this.utils.request.liveRequest({
                url: '/api/v1/broadcast/anchorInfo',
                method: 'post',
                params: this.addDataForm
              }).then(result => {
                let data = result.data;
                if (data.code === '0') {
                  this_.$refs.CyTable.findPage(this_.dataForm)
                  this_.$forceUpdate();
                  this.dialogClose();
                }
                this_.addLoading=false;
              })
            });
          }
        });
      },
      dialogClose(){
        this.dialogVisibleAdd=false;
        this.$refs.addDataForm.resetFields()
        this.addDataForm.handPhoto = '';
      },
      fileUploadSuccess(res, file) { // 文件上传成功回调
        this.addDataForm.handPhoto = res.data;
      },
      beforeAvatarUpload(file) {
        // 限制图片大小
        const isSize = new Promise((resolve,reject)=> {
          let width = 1920;
          let height = 1080;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            let valid = img.width == width && img.height == height
            valid ? resolve() : reject();
          }
        })
          .then(()=>{
            return file;
          },()=>{
            this.$message.error('上传图片像素格式为1920*1080!');
            return Promise.reject();
          })
        return isSize;
      }
    }
  }
</script>
<style scoped lang="scss">

</style>
